package api;

import java.util.HashMap;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import beans.ApiRequest;
import beans.ApiResponse;
import beans.ApiResponseSync;
import beans.SendSmsBean;
import beans.SendSmsResBean;
import enums.ApiStatus;
import enums.CmdType;
import helper.LogHelper;
import helper.WebHelper;

public class SendSmsApi {
	private LogHelper logger = new LogHelper();
	private ApiRequest<SendSmsBean> request = new ApiRequest<SendSmsBean>();
	
	/**
	 * 同步发送短信
	 * @param url 发送地址
	 * @param sendSmsBean 发送消息内容
	 * @param companyNo 公司编号
	 * @param token 令牌
	 * @param privateKey 私钥
	 * @throws Exception 
	 * @apiNote 本例为同步提交短信，同步提交只适用于点对点发送，批量提交可能导致性能降低，建议使用异步发送方法批量提交
	 * */
	public SendSmsResBean SendSms(String url, SendSmsBean sendSmsBean, String companyNo, String token) throws Exception {
		request.setCmdType(CmdType.SendSms);
		request.setData(sendSmsBean);
		Gson gson = new Gson();
		String data = gson.toJson(request).replace(" ", "").replaceAll("(\\r\\n|\\r|\\n|\\n\\r)", "");
		System.out.println(data);
		HashMap<String, String> headers = WebHelper.GetHeaders(companyNo, token, data);
		String res = WebHelper.SendPost(url, data, headers);
		System.out.println(res);
		ApiResponse<SendSmsResBean> info = gson.fromJson(res, new TypeToken<ApiResponse<SendSmsResBean>>() {}.getType());
//		System.out.println("发送响应状态：" + ApiStatus.codeOf(info.getApiStatus()));
		
		if(info.getError() != "" && info.getError() != null) {
			logger.Debug(SendSmsApi.class.getName() + ".SendTemplateSms", info.getError());
			throw new Exception("getError: "+info.getError());
		}
		return info.getData();
	}
	/**
	 * 异步发送短信
	 * @param url 发送地址
	 * @param sendSmsBean 发送消息内容
	 * @param companyNo 公司编号
	 * @param token 令牌
	 * @param privateKey 私钥
	 * @throws Exception 
	 * @apiNote 本例为异步提交短信，适用于批量发送，每次提交控制在1000个号码以内
	 * */
	public ApiResponseSync SendSync(String url, SendSmsBean sendSmsBean, String companyNo, String token) throws Exception {
		Gson gson = new Gson();
		String data = gson.toJson(sendSmsBean).replace(" ", "").replaceAll("(\\r\\n|\\r|\\n|\\n\\r)", "");
		System.out.println(data);
		HashMap<String, String> headers = WebHelper.GetHeaders(companyNo, token, data);
		String res = WebHelper.SendPost(url, data, headers);
		System.out.println(res);
		ApiResponseSync info = gson.fromJson(res, new TypeToken<ApiResponseSync>() {}.getType());
//		System.out.println("发送响应状态：" + info.getResult());
		
		if(info.getError() != "" && info.getError() != null) {
			logger.Debug(SendSmsApi.class.getName() + ".SendTemplateSms", info.getError());
			throw new Exception("getError: "+info.getError());
		}
		return info;
	}
}
